import { loginApi, getUserInfoApi } from '@/api/user'
import { getToken, setToken, removeToken, setuserId, getuserId, removeuserId } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    userid: getuserId(),
    userInfo:{}
  }
}

const state = getDefaultState()

const mutations = {
  updateToken(state, token) {
    state.token = token
    setToken(token)
  },
  updateUserid(state, id) {
    state.userid = id
    setuserId(id)
  },
  delToken(state) {
    removeToken()
    state.token = null
    removeuserId()
    state.userid = null
  },
  deluserInfo(state, data) {
    state.userInfo = data
  }

}

const actions = {
  async login(context, data) {
    const res = await loginApi(data)
    context.commit('updateToken',res.token)
    context.commit('updateUserid',res.userId)
  },
  async getUserInfo({state}) {
    const res = await getUserInfoApi(state.userid)
    state.userInfo = res
  },
  logout({commit}) {
    commit('delToken')
    commit('deluserInfo',{})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

